﻿using Microsoft.AspNetCore.DataProtection;
using SkiaSharp;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace XinLife.Core.Helper
{
    public class ImageCropper
    {
        public static (string, string, int) CropImage(string imagePath, int width, int height)
        {
            string org_Img = "";
            string cro_Img = "";
            int cro_x = 0;
            //加载原始图片
            using (var originalBitmap = SKBitmap.Decode(imagePath))
            {
                // 随机选择剪裁位置
                var random = new Random();
                var x = random.Next(100, originalBitmap.Width - width);
                var y = 100;//random.Next(0, originalBitmap.Height - height);
                cro_x = x;
                // Define the source and destination rectangles
                var srcRect = new SKRectI(x, y, x + width, y + height);
                var destRect = new SKRectI(0, 0, width, height);

                // 剪裁后的原图片
                using (SKBitmap modifiedBitmap = new SKBitmap(originalBitmap.Width, originalBitmap.Height))
                {
                    using (SKCanvas canvas = new SKCanvas(modifiedBitmap))
                    {
                        // 绘制原图片
                        canvas.DrawBitmap(originalBitmap, 0, 0);
                        // 在指定位置绘制空白矩形
                        using (SKPaint paint = new SKPaint())
                        {
                            paint.Color = SKColors.White;
                            canvas.DrawRect(srcRect, paint);
                        }
                    }
                    // 保存修改后的图片
                    using (SKImage image = SKImage.FromBitmap(modifiedBitmap))
                    using (SKData data = image.Encode())
                        org_Img = Convert.ToBase64String(data.ToArray());
                }

                // 剪裁的图片
                using (var croppedBitmap = new SKBitmap(width, height))
                {
                    // 剪裁图片
                    using (var canvas = new SKCanvas(croppedBitmap))
                    {
                        canvas.DrawBitmap(originalBitmap, srcRect, destRect);
                    }
                    // Save the cropped image to file
                    using (var image = SKImage.FromBitmap(croppedBitmap))
                    using (var data = image.Encode())
                        cro_Img = Convert.ToBase64String(data.ToArray());
                    //var stream = System.IO.File.OpenWrite(outputPath))
                    //{
                    //    data.SaveTo(stream);
                    //}
                }
                return (org_Img, cro_Img, cro_x);
            }
        }
    }
}